package com.yiren.dbaa.module.practice_set.map.presenter;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;

import com.yiren.backstage.config.api.LoadConfigApi;
import com.yiren.backstage.config.bean.device.UserParamConfigBean;
import com.yiren.backstage.currency.constant.DbConstant;
import com.yiren.backstage.currency.entity.MapEntity;
import com.yiren.backstage.currency.utils.FileUtil;
import com.yiren.backstage.currency.utils.StringUtil;
import com.yiren.backstage.db.dao.controller.UserDbController;
import com.yiren.dbaa.constant.AddressConstant;
import com.yiren.dbaa.currency.api.CommonCallBack;
import com.yiren.dbaa.currency.dialog.CommonDialog;
import com.yiren.dbaa.module.practice_set.map.bean.LineBindBean;
import com.yiren.dbaa.module.practice_set.map.contract.MapHomeContract;
import com.yiren.dbaa.module.practice_set.map.contract.MapReleaseContract;
import com.yiren.dbaa.module.practice_set.map.model.MapHomeModel;
import com.yiren.dbaa.module.practice_set.map.model.MapReleaseModel;
import com.yiren.dbaa.module.practice_set.PracticeCarSetActivity;
import com.yiren.dbaa.net.bean.OSSResultBean;
import com.yiren.dbaa.util.ZipUtils;
import com.yiren.dbaa.view.dialog.LoadDialog;
import com.yiren.dbaa.view.toast.MessageBox;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author lwb
 * @date : 2022/11/30 14:03
 * @description: 地图发布
 */
public class MapReleasePresenter implements MapReleaseContract.Presenter {

    private Activity activity;
    private MapReleaseContract.Model mapReleaseModel;
    private MapHomeContract.Model mapHomeModel;
    private UserParamConfigBean userParamConfig;

    public MapReleasePresenter(Activity activity) {
        this.activity = activity;
        mapReleaseModel = new MapReleaseModel(activity);
        mapHomeModel = new MapHomeModel(activity);
        userParamConfig = LoadConfigApi.loadUserParamConfig(activity);
    }

    @Override
    public void releaseMapToSer(MapEntity map, List<LineBindBean> lines, MapReleaseContract.View view) {
        //首次发布设置范围为全部用户
        if (map.getMapVer() == 0) {
            map.setUseRange(2);
        }
        String message;
        if (map.getMapVer() < map.getMapVerLast()) {
            message = "确定将版本回退到V" + map.getMapVer() + "吗?";
        } else {
            message = "发布前请验证，避免用户更新导致无法正常使用， 确定现在发布?";
        }
        CommonDialog.showTwoBtn(activity, "操作确认", message, "取消", "发布", (dialog, which) -> {
            dialog.dismiss();
            if (which != -2) {
                activity.runOnUiThread(() -> LoadDialog.show(activity, "正在发布中，请稍后..."));
                //数据文件
                String mapDataDir = AddressConstant.App_Main_Directory() + userParamConfig.getUserInfo().getId() + "/map/" + map.getSiteCode() + "/";
                String mapDataUrl = mapDataDir + DbConstant.TRAJECT_DATA_NAME;
                File oldFile = new File(mapDataUrl);
                if (oldFile.exists()) {  //有轨迹数据，先上传OSS，再发布地图
                    mapHomeModel.getDataDirAuth(new CommonCallBack() {
                        @Override
                        public void success(Object result) {
                            OSSResultBean ossResultBean = (OSSResultBean) result;
                            //新建一个临时目录存放复制过来的文件
                            String tempDataDir = AddressConstant.App_Main_Directory() + userParamConfig.getUserInfo().getId() + "/map/zip";
                            File tempFile = new File(tempDataDir);
                            if (!tempFile.exists()) {
                                tempFile.mkdir();
                            }
                            String tempDataUrl = tempDataDir + "/" + DbConstant.TRAJECT_DATA_NAME;
                            FileUtil.copyFile(mapDataUrl, tempDataUrl);
                            String zipFileName = map.getMapVer() + ".zip";
                            String dataZipFile = tempDataDir + "/" + zipFileName;
                            try {
                                ZipUtils.zipFile(new File(tempDataUrl), new File(dataZipFile));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                            mapHomeModel.uploadSiteMap(ossResultBean, userParamConfig.getUserInfo().getId(), map.getSiteCode(), zipFileName, dataZipFile, new CommonCallBack() {
                                @Override
                                public void success(Object result) {
                                    FileUtil.deleteAll(tempDataDir);
                                    //上传轨迹成功，发布地图
                                    releaseMapData(map, lines, view);
                                }

                                @Override
                                public void fail(String error) {
                                    FileUtil.deleteAll(tempDataDir);
                                    LoadDialog.dismiss(activity);
                                    MessageBox.show(activity, error);
                                }
                            });
                        }

                        @Override
                        public void fail(String error) {
                            LoadDialog.dismiss(activity);
                            MessageBox.show(activity, error);
                        }
                    });
                } else {
                    //没有轨迹数据，直接发布地图
//                  MessageBox.show(activity, "轨迹数据为空，请采集轨迹或者恢复默认！");
                    releaseMapData(map, lines, view);
                }
            }
        });
    }

    /**
     * 发布地图数据
     *
     * @param map
     */
    private void releaseMapData(MapEntity map, List<LineBindBean> lines, MapReleaseContract.View view) {
        mapReleaseModel.publishMap(map, userParamConfig.getUserInfo().getId(), new CommonCallBack() {
            @Override
            public void success(Object result) {
                map.setMapVer(map.getMapVerLast() + 1);
                UserDbController.getInstance(false).update(map);
                if (null != lines && lines.size() > 0) {
                    mapReleaseModel.updateMapBindLines(map.getId(), lines, new CommonCallBack() {
                        @Override
                        public void success(Object result) {
                            LoadDialog.dismiss(activity);
                            view.releaseMapSuccess();
                        }

                        @Override
                        public void fail(String error) {
                            MessageBox.show(activity, error);
                        }
                    });
                } else {
                    LoadDialog.dismiss(activity);
                    view.releaseMapSuccess();
                }
            }

            @Override
            public void fail(String error) {
                LoadDialog.dismiss(activity);
                activity.runOnUiThread(() -> CommonDialog.showOneBtn(activity, "操作提示", "地图数据发布失败!", "我知道了", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }));
            }
        });
    }

}